﻿#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickStyle>
#include <QUuid>
#include <QDebug>

#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>

#include "myprogressbarmodel.h"
#include <JQHttpServer>

static MyProgressBarModel* g_model = nullptr;

void onHttpAccepted(const QPointer< JQHttpServer::Session > &session)
{
    // 回调发生在专用的处理线程内，不是主线程，也不是socket的生存线程，请注意线程安全
    // 若阻塞了此回调，那么新的连接将被阻塞（默认情况下有2个线程可以阻塞2次，第3个连接将被阻塞）

    QString requestUrl(session->requestUrl());
    QString requestBody(session->requestBody());
    QString text = QString( "url:%1\nbody:%2" ).arg( requestUrl, requestBody );

    //    session->replyRedirects( QUrl( "http://www.baidu.com" ) );
    //    session->replyJsonObject( { { { "message", "ok" } } } );
    //    session->replyJsonArray( { "a", "b", "c" } );
    //    session->replyFile( "/Users/jason/Desktop/Test1.Test2" );
    //    session->replyImage( QImage( "/Users/jason/Desktop/Test.png" ) );
    //    session->replyBytes( QByteArray( 4,'\x24' ), "text" ); // $$$$

    // 注1：因为一个session对应一个单一的HTTP请求，所以session只能reply一次
    // 注2：在reply后，session的生命周期不可控，所以reply后不要再调用session的接口了
    session->replyText( text );

    if (g_model)
    {
        emit g_model->myDataChanged(requestBody);
    }
}

void initializeHttpServer()
{
    static JQHttpServer::TcpServerManage tcpServerManage( 2 ); // 设置最大处理线程数，默认2个
    tcpServerManage.setHttpAcceptedCallback( std::bind( onHttpAccepted, std::placeholders::_1 ) );
    QObject::connect(qApp, &QCoreApplication::aboutToQuit, &tcpServerManage, &JQHttpServer::AbstractManage::deinitialize);

    const auto listenSucceed = tcpServerManage.listen( QHostAddress::Any, 23412 );
    qDebug() << "HTTP server listen:" << listenSucceed;
}

int main(int argc, char *argv[])
{
    qputenv( "QT_SSL_USE_TEMPORARY_KEYCHAIN", "1" );
    qSetMessagePattern( "%{time hh:mm:ss.zzz}: %{message}" );

    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    QQmlContext *ctxt = engine.rootContext();

//    qmlRegisterType<MyData>("MyData", 1, 0, "MyData");
    MyProgressBarModel model;
//    for (int i = 0; i <= 10; i++)
//    {
//        MyData data;
//        data.m_nStep = i * 10;
//        data.m_nTotal = 100;

//        QUuid id = QUuid::createUuid();
//        data.m_strUuid = id.toString();
//        data.m_strText = "test";
//        model.append(data);
//    }

    g_model = &model;
    ctxt->setContextProperty("myModel", &model);

//    engine.rootContext()->setContextProperty("availableStyles", QQuickStyle::availableStyles());
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    initializeHttpServer();

    return app.exec();
}
